from models import *
from google.appengine.api import memcache
from appengine_utilities.sessions import Session

class MemcacheError(Exception):
	def __init__(self, value):
		self.value = value
	
	def __str__(self):
		return repr(self.value)
		
class DatastoreError(Exception):
	def __init__(self, value):
		self.value = value
	
	def __str__(self):
		return repr(self.value)
		
class IncorrectPasswordError(Exception):
	def __init__(self, value):
		self.value = value
	
	def __str__(self):
		return repr(self.value)		

class UserDAO:
	'''
	Class to access User objects on the datastore.
	
	@author: guiocavalcanti
	'''
	
	def __init__(self):
		self.allUsers = User.all()
	
	def getUser(self, username, password):
		'''
		Search the user with especified username on memcache, if it
		fails look on the datastore.
		
		@param username: The username you are looking for
		@return: User or None
		@raise DatastoreError: If user doesnt exists on datastore
		'''
		
		try:
			# Trying to get user on memcache.
			user = self.__getFromSession(username, password)
			return user
		
		except MemcacheError:
			# If it isnt on memcache, search on the datastore.
			try:
				user = self.__getFromDB(username, password)
				self.addUserToSession(user.getUsername(), user)
				return user
				
			# In case that user doesnt exists at all, raise an DatastoreError.
			except DatastoreError:
				raise
			
			# In case tha user's password doesnt match, raise an IncorrectPasswordError.
			except IncorrectPasswordError:
				raise
		# In case tha user's password doesnt match, raise an IncorrectPasswordError.		
		except IncorrectPasswordError:
			raise
		
	def __getFromSession(self, username, password):
	
		user = memcache.get(username)
		if user:
			if user.checkPass(password):
				return user
			else:
				raise IncorrectPasswordError('The password given doesnt match')
		else: 
			raise MemcacheError('User doesnt exists on session')
		
	def __getFromDB(self, username, password):
		
		user = User.all().filter('username =', username).get()
		if user:
			if user.checkPass(password):
				return user
			else:
				raise IncorrectPasswordError('The password given doesnt match')
		else:
			raise DatastoreError('User doesnt exists on datastore')
		
			
	def addUserToSession(self, key, user):
		'''
		Add user to memcache.
		
		@type user: User
		@param key: The key of user object. Usually the username.
		@param user: The User object
		'''
		
		#TODO define what is gonna be on session
		memcache.set(user.getUsername(), user)
		
		
		
